package com.weilele.mvvm.utils

import com.weilele.mvvm.base.helper.getParameterizedType
import com.weilele.mvvm.base.helper.ignoreError
import com.weilele.mvvm.gson
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

open class ClassType<T> {
    val type: Type? =
            ignoreError {
                this.javaClass.getParameterizedType()
                        ?.actualTypeArguments
                        ?.get(0)
            }
}

/**
 * 针对于泛型，获取真实的类型
 * eg:
 *  val s="[1,2,3,4,5]"
 *  val s1=gson.fromJson<List<String>>(s, getRealClassType<List<String>>())
 */
inline fun <reified T> getRealClassType(): ParameterizedType? {
    return object : ClassType<T>() {}.type.safeGet()
}

/**
 * 对象转为json格式字符串
 */
fun Any.toJsonString(): String {
    return gson.toJson(this)
}

/**
 * json格式字符串，转对象
 */
inline fun <reified T> String.formJsonString(checkRealType: Boolean = false/*针对泛型，是否获取真正的cls*/): T {
    val realClassType = if (checkRealType) {
        getRealClassType<T>()
    } else {
        null
    }
    return if (realClassType == null) {
        gson.fromJson(this, T::class.java)
    } else {
        gson.fromJson(this, realClassType)
    }
}